(function () {

    let loginEle = document.getElementById('login');
    let loginInput = loginEle.getElementsByTagName('input')[0];
    let loginSubmit = loginEle.getElementsByTagName('span')[0];

    let roomsEle = document.getElementById('rooms');

    let chessBox = document.getElementById('chess-box');
    let chesses = document.getElementById('chesses');

    let infoBox = document.getElementById('info-box');
    let userInfo = document.getElementById('user-info');
    let chessInfo = document.getElementById('chess-info');
    let tipsBox = document.getElementById('tips-box');

    let bottomBox = document.getElementById('bottom-box');

    let chatZoom = document.getElementById('chat-zoom');
    let chatList = document.getElementById('chat-list');
    let chatControl = document.getElementById('chat-control');
    let chatSendText = chatControl.getElementsByTagName('input')[0];
    let chatSendMethod = chatControl.getElementsByTagName('span')[0];
    let chatSendBtn = chatControl.getElementsByTagName('span')[1];
    let chatBtnGroup = document.getElementById('chat-btn-group');
    let chatBtnViewport = chatBtnGroup.getElementsByTagName('span')[0];

    let optsZoom = document.getElementById('opts-zoom');
    let optsUsername = document.getElementById('opts-username');
    let optsBtnGroup = document.getElementById('opts-btn-group');

    // 'user token'
    let userToken;
    // flag
    let hasEnterRoom = false;
    let sendingChat = false;
    // 节流：房间列表, 发起和棋，发送消息，点击按钮组
    let getRoomsTimer, gamePeaceTimer, sendChatTimer, clickTimer;

    // ws服务器：url:port
    let wsUrl = 'ws://localhost:8081'
    // let wsUrl = 'ws://182.61.38.152/:8081'

    // 底部按钮组：房间列表页
    let optsConf1 = {
        'createRoom': {
            content: '创建',
            onclick: enterRoom,
            hidden: false,
            icon: 'create',
        },
        'qiuckJoin': {
            content: '匹配',
            onclick: enterRoom,
            hidden: false,
            icon: 'quick',
        },
        'quite': {
            content: '退出',
            onclick: quite,
            hidden: false,
            icon: 'quit',
        },
    };

    // 底部按钮组：房间游戏页
    let optsConf2 = {
        'ready': {
            content: '准备',
            onclick: gameReady,
            hidden: false,
            icon: 'ready',
        },
        'start': {
            content: '开始',
            onclick: gameReady,
            hidden: true,
            icon: 'ready',
        },
        'defeat': {
            content: '认输',
            onclick: gameDefeat,
            hidden: true,
            icon: 'defeat',
        },
        'peace': {
            content: '和棋',
            onclick: gamePeace,
            hidden: true,
            icon: 'peace'
        },
        'quite': {
            content: '离开',
            onclick: quiteRoom,
            hidden: false,
            icon: 'out',
        },
    };

    window.onload = function () {

        // 初始显隐
        roomsEle.setAttribute('hidden', true);
        chessBox.setAttribute('hidden', true);
        infoBox.setAttribute('hidden', true);
        bottomBox.setAttribute('hidden', true);

        // 首页：绑定事件
        loginSubmit.addEventListener('click', login, false)
        loginInput.addEventListener('keydown', () => {
            window.event.stopPropagation();
            if (window.event.keyCode == 13) {
                window.event.preventDefault();
                login();
            }
        }, false)

    }

    function login() {
        // 表单验证
        let inputValue = loginInput.value.trim();
        if (!inputValue || inputValue.length > 6 || inputValue.length < 2) {
            return
        }

        // 连接服务器
        $game.init(wsUrl, inputValue, null, render).then(() => {
            // 登录成功，验证成功，用户合法
            // 获取房间
            getRooms();
        });
    }

    // 渲染总接口
    function render(r) {
        console.log(r);
        switch (r.method) {
            case 'init':
                renderSignIn(r.data);
                break;
            case 'rooms':
                renderRoomsList(r.data, enterRoom)
                break;
            case 'enter':
                renderEnterRoom(r.data)
                break;
            case 'ready':
                renderReady(r.data);
                break;
            case 'start':
                renderStart(r.data);
                break;
            case 'move':
            case 'eat':
                $render.chesses(chesses, r.data, $game.pickChess);
                $render.infoBoxChess(chessInfo, r.data);
                break;
            case 'defeat':
            case 'winner':
                renderGameOver(r.data);
                break;
            case 'out':
                // 玩家(别人)退出房间，重新渲染房间
                renderRefreshRoom(r.data);
                break;
            case 'tip':
                $render.infoBoxTips(tipsBox, r.data, 3000)
                break;
            case 'all':
                if (!hasEnterRoom) {
                    $render.chatItem(chatList, r)
                }
                break;
            case 'many':
                if (hasEnterRoom) {
                    $render.chatItem(chatList, r)
                }
                break;
        }
    }

    // 登录成功，首次渲染
    function renderSignIn(data) {
        // 缓存用户信息
        userToken = data;
        // 隐藏登录页，显示房间列表页，底部页
        loginEle.setAttribute('hidden', true);
        roomsEle.removeAttribute('hidden');
        bottomBox.removeAttribute('hidden');
        // 底部按钮组
        optsUsername.innerText = data.name;
        $render.optsGroup(optsBtnGroup, optsConf1);
        // 聊天事件绑定
        chatSendBtn.addEventListener('click', sendChat);
        chatSendText.addEventListener('keydown', () => {
            window.event.stopPropagation();
            if (window.event.keyCode == 13) {
                window.event.preventDefault();
                sendChat();
            }
        }, false)
        // 聊天按钮组
        chatBtnViewport.addEventListener('click', function () {
            let event = window.event;
            chatListViewport();
            if (event.target.innerText == '展开') {
                event.target.innerText = "收起";
            } else {
                event.target.innerText = "展开";
            }
        })
    }

    function getRooms() {
        clearInterval(getRoomsTimer);
        getRoomsTimer = setInterval(() => {
            // 获取房间
            $game.getRooms();
        }, 1500)
    }

    function pauseGetRooms() {
        clearInterval(getRoomsTimer);
    }

    function renderRoomsList(data, enterFn) {
        $render.rooms(roomsEle, data, enterFn);
    }

    function enterRoom(id) {
        if (typeof id == 'object') {
            $game.createRoom().then(() => {
                // flag：进入房间
                hasEnterRoom = true;
                togChatMethod();
            })
            return
        }
        $game.enterRoom(id).then(() => {
            // flag：进入房间
            hasEnterRoom = true;
            togChatMethod();
        })
    }

    function renderEnterRoom(room) {
        // 停止获取房间列表
        pauseGetRooms();

        // 显示棋盘页、信息页，隐藏房间列表页
        roomsEle.setAttribute('hidden', true);
        chessBox.removeAttribute('hidden');
        infoBox.removeAttribute('hidden');

        // 房间信息、游戏信息
        $render.infoBoxUser(userInfo, room);
        $render.infoBoxChess(chessInfo, room);

        // 如果已开局，渲染棋子，(tips: 房主开始游戏渲染棋子)
        if (room.start) {
            $render.chesses(chesses, room, $game.pickChess);
        }

        // 底部功能区
        if (room.user[0] && room.user[0].token == userToken.token) {
            // 房主
            optsConf2['ready'].hidden = true;
            optsConf2['start'].hidden = false;
        } else if (room.user[1] && room.user[1].token == userToken.token) {
            // 对手
            optsConf2['ready'].hidden = false;
            optsConf2['start'].hidden = true;
        } else {
            // 观战
            optsConf2['ready'].hidden = true;
            optsConf2['start'].hidden = true;
        }
        $render.optsGroup(optsBtnGroup, optsConf2);
    }

    // 刷新房间
    function renderRefreshRoom(room){
        // 房间信息、游戏信息
        $render.infoBoxUser(userInfo, room);
        $render.infoBoxChess(chessInfo, room);

        // 如果已开局，渲染棋子，(tips: 房主开始游戏渲染棋子)
        if (room.start) {
            $render.chesses(chesses, room, $game.pickChess);
        }

        // 底部功能区
        if (room.user[0] && room.user[0].token == userToken.token) {
            // 房主
            optsConf2['ready'].hidden = true;
            optsConf2['start'].hidden = false;
        } else if (room.user[1] && room.user[1].token == userToken.token) {
            // 对手
            optsConf2['ready'].hidden = false;
            optsConf2['start'].hidden = true;
        } else {
            // 观战
            optsConf2['ready'].hidden = true;
            optsConf2['start'].hidden = true;
        }
        $render.optsGroup(optsBtnGroup, optsConf2);
    }

    // 准备，开始
    function gameReady() {
        $game.ready();
    }

    function renderReady(room) {
        if (room.user[1].token == userToken.token) {
            // 非房主准备
            if (room.ready) {
                optsConf2['ready'].content = '取消';
            } else {
                optsConf2['ready'].content = '准备';
            }
            $render.optsGroup(optsBtnGroup, optsConf2);
        } else {
            // 房主、观战  (提示信息)
            if (room.ready) {
                $render.infoBoxTips(tipsBox, '对手已准备')
            } else {
                $render.infoBoxTips(tipsBox, '对手取消准备')
            }
        }

        $render.infoBoxChess(chessInfo, room);
    }

    function renderStart(room) {
        if (room.user[0].token == userToken.token || room.user[1].token == userToken.token) {
            // 房主准备(开始)，游戏开始，房主和对手的界面：认输
            optsConf2['ready'].hidden = true;
            optsConf2['start'].hidden = true;
            optsConf2['defeat'].hidden = false;
            // optsConf2['peace'].hidden = false;
            $render.optsGroup(optsBtnGroup, optsConf2);
        } else {
            // 观战

        }
        $render.chesses(chesses, room, $game.pickChess);
        $render.infoBoxChess(chessInfo, room);
    }

    function renderGameOver(room) {

        // 棋子
        // $render.chesses(chesses, room, $game.pickChess);
        // 棋子已清空，直接为空，"开始"后会重置棋子
        chesses.innerHTML = '';

        // 房间信息、游戏信息
        $render.infoBoxUser(userInfo, room);
        $render.infoBoxChess(chessInfo, room);

        // 底部按钮组
        if (room.user[0].token == userToken.token) {
            // 房主
            optsConf2['defeat'].hidden = true;
            optsConf2['peace'].hidden = true;
            optsConf2['start'].hidden = false;
        } else if (room.user[1].token == userToken.token) {
            // 对手
            optsConf2['defeat'].hidden = true;
            optsConf2['peace'].hidden = true;
            optsConf2['ready'].hidden = false;
            if (room.ready) {
                optsConf2['ready'].content = '取消';
            } else {
                optsConf2['ready'].content = '准备';
            }
        } else {
            // 观战，不更新按钮组，(更新清空棋子和信息栏)
            return
        }
        $render.optsGroup(optsBtnGroup, optsConf2);
    }

    // 离开房间
    function quiteRoom() {
        $game.quiteRoom().then(() => {

            // 重置棋盘以及信息栏
            chesses.innerHTML = '';
            // userInfo.innerHTML = "<div class='icon-vs'></div>";
            // chessInfo.innerHTML = "<div id='tips-box'></div>";
            tipsBox.innerHTML = "";
            // 显示房间列表页，隐藏棋子页、信息页
            chessBox.setAttribute('hidden', true);
            infoBox.setAttribute('hidden', true);
            roomsEle.removeAttribute('hidden');

            // 底部按钮组
            $render.optsGroup(optsBtnGroup, optsConf1);

            // 获取房间列表
            getRooms();

            // flag：退出房间
            hasEnterRoom = false;
            // 切换聊天"世界"模式
            togChatMethod();
        });
    }

    // 发送聊天消息
    function sendChat() {
        let value = chatSendText.value.trim();

        if (!value || sendingChat) return
        sendingChat = true;

        let method = chatSendMethod.getAttribute('data-method');
        $game.sendChat(method, value);
        chatSendText.value = '';

        clearInterval(sendChatTimer)
        sendChatTimer = setInterval(() => {
            sendingChat = false;
        }, 1200);
    }

    // 转换聊天发送method：all、many
    function togChatMethod() {
        let method = chatSendMethod.getAttribute('data-method');
        if (method == 'all') {
            chatSendMethod.setAttribute('data-method', 'many');
            chatSendMethod.innerText = '[房间]';
        } else {
            chatSendMethod.setAttribute('data-method', 'all');
            chatSendMethod.innerText = '[世界]';
        }
    }

    // 转换聊天列表窗口：大、小
    function chatListViewport() {
        let classList = chatList.classList;
        if (classList.contains('simple')) {
            classList.remove('simple');
        } else {
            classList.add('simple');
        }
        // 一直在底部
        chatList.scrollTop = chatList.scrollHeight;
    }


    // 认输
    function gameDefeat() {
        $game.defeat();
    }

    // 和棋
    function gamePeace() {

    }

    // 退出登录，离开
    function quite() {
        window.location.reload();
    }

})()